package poswar.contribute.dao;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;

import poswar.contribute.model.Question;
import poswar.contribute.util.Config;
import poswar.contribute.util.FriendModeManager;

public class QuestionDao {
	private static final Logger logger = Logger.getLogger(QuestionDao.class);

	String XML_FILE = Config.getXmlPath() + "/question-data.xml";

	public void save(Question question) {
		// Create a File to marshal to
		try {
			FileWriter writer = new FileWriter(XML_FILE);

			// Marshal the person object
			Marshaller.marshal(question, writer);
			writer.close();
		} catch (Exception e) {
			// FIXME - Create exception
			throw new RuntimeException("Error saving question data", e);
		}
	}

	public Question load() {		
		if (logger.isDebugEnabled()) {
			logger.debug("reading file: " + XML_FILE);
		}
		
		FileReader reader = null; 
		try {
			final FileReader innerReader = new FileReader(XML_FILE);
			reader = innerReader;
			Question question = FriendModeManager.callInFriendMode(new Callable<Question>() {		
				@Override
				public Question call() throws Exception {
					return (Question) Unmarshaller.unmarshal(Question.class, innerReader);
				}			
			});
			
			return question;
		} catch (Exception e) {
			logger.warn("Error loading question data", e);
			logger.info("No data was loaded. Starting a new question");
			
			Question question = new Question();
			return question;
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				logger.warn("Error loading board data", e);
			}
		}
	}

	public void backup(Question question) {
		
		File srcFile = new File(XML_FILE);
		File destFile = createNewFile(XML_FILE);
		try {
			FileUtils.copyFile(srcFile, destFile);
		} catch (IOException e) {
			throw new RuntimeException("Error saving question data", e);
		}
		
	}

	private File createNewFile(String fileName) {
		String suffix = fileName.substring(0, fileName.lastIndexOf(".xml"));
		
	    int i = 1;
	    String filename = suffix + "-" + i + ".xml";
	    File f = new File(filename);
	    while (f.exists()) {
	        i++;
	        filename = suffix + "-" + i + ".xml";
	        f = new File(filename);
	    }
	    return f;
	}

}
